package admin

import (
	"fmt"
	"math"
	"strconv"
	"strings"
	"tcsc/controllers/mobile"
	"tcsc/models"
	"tcsc/sword"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type TestFloat struct {
	beego.Controller
}

func (c *TestFloat) Get() {
	c.EnableRender = false
	product := models.Query(`select id,content from mt_product where status=1 and censoring=1`)
	for _, v := range product {
		content := fmt.Sprint(v["content"])
		content2 := strings.Replace(content, `https://www.tongcaigou.com/includes/ueditor/php/../../../images/image/`, `/static/images/image/`, -1)
		if content != content2 {
			err := models.Exec(`update mt_product set content=? where id=?`, content2, v["id"])
			if err != nil {
				beego.Debug(err)
			}
		}
	}
}

type ActiveCoupon struct {
	BaseController
}

func (c *ActiveCoupon) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.gid=`+c.Gid)
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.sort desc,a.addtime desc`
	sql := `select a.*,c.pathname from 
	mt_coupon a 
	left join mt_resources c on a.img=c.id 
	where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_coupon a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/active/coupon?`
	c.TplName = "admin/active/coupon.html"
}

type ActiveCouponAE struct {
	BaseController
}

func (c *ActiveCouponAE) Get() {
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.*,b.pathname from mt_coupon a 
			left join mt_resources b on a.img=b.id 
			where a.id=` + id + ` and a.gid=` + c.Gid); info != nil {
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, "/admin/active/coupon")
		}
	}
	c.TplName = "admin/active/coupon_ae.html"
}
func (c *ActiveCouponAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	input.Set("gid", c.Gid)
	if res, err := models.Save("mt_coupon", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 39
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type ActiveGbuy struct {
	BaseController
}

func (c *ActiveGbuy) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.gid=`+c.Gid)
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.sort desc,a.addtime desc`
	sql := `select a.*,b.title as pname,c.pathname from mt_active_gbuy a left join mt_product b on a.pid=b.id left join mt_resources c 
	on b.img=c.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_active_gbuy a where ` + ws
	info := models.Query(sql)
	for _, v := range info {
		if order := models.Query(`select count(a.id) as jnum,sum(b.num) as jgnum from mt_order a join mt_order_car b on a.carid=b.id 
			where a.type=1 and a.status>=2 and a.agid=` + v["id"].(string) + ` group by(a.id)`); order != nil {
			v["jnum"] = order[0]["jnum"]
			if order[0]["jgnum"] == nil {
				v["jgnum"] = "0"
			} else {
				v["jgnum"] = order[0]["jgnum"]
			}
		} else {
			v["jnum"] = "0"
			v["jgnum"] = "0"
		}
	}
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/active/gbuy?`
	c.Data["vip"] = models.Query(`select id,name from mt_member_vip where gid=0 and status=1`)
	c.TplName = "admin/active/gbuy.html"
}

type ActiveGbuyAE struct {
	BaseController
}

func (c *ActiveGbuyAE) Get() {
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.* from mt_active_gbuy a where a.id=` + id); info != nil {
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, "/admin/active/gbuy")
		}
	}
	c.TplName = "admin/active/gbuy_ae.html"
}
func (c *ActiveGbuyAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
		input.Set("gid", c.Gid)
	}
	if res, err := models.Save("mt_active_gbuy", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 64
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type ActiveGbuyJoin struct {
	BaseController
}

func (c *ActiveGbuyJoin) Get() {
	id := c.GetString("id")
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status>1`)
	w = append(w, `a.type=1`)
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc`
	sql := `select a.*,b.title,c.monicker,d.pathname,e.num as jnum from mt_order a left join mt_active_gbuy b on a.agid=b.id left join mt_member c 
	on a.uid=c.id left join mt_resources d on c.avatar=d.id left join mt_order_car e on a.carid=e.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_order a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/active/gbuy_join?id=` + id + `&`
	c.TplName = "admin/active/gbuy_join.html"
}

type ActiveGbuyRet struct {
	BaseController
}

func (c *ActiveGbuyRet) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	if err := models.Exec(`update mt_active_gbuy set end=1 where id=` + c.GetString("id")); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		return
	}
	o := models.Orm()
	o.Begin()
	order := models.Query(`select * from mt_order where status=2 and agid=` + id)
	for _, v := range order {
		oid := v["id"].(string)
		uid := v["uid"].(string)
		money_detail := models.Query(`select * from mt_member_money_detail where oid=` + oid + ` and type=3`)[0]
		ptype := fmt.Sprint(money_detail["paytype"])
		rprice := fmt.Sprint(money_detail["money"])
		if _, err := o.Raw("update mt_order set status=6 where id=" + oid).Exec(); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		}
		if _, err := o.Raw("update mt_order_car set `return`=1 where id=" + id).Exec(); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		}
		switch ptype {
		case "1":
			if _, err := o.Raw(`update mt_member set money=money+` + rprice + ` where id=` + uid).Exec(); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
				o.Rollback()
				return
			}
			if _, err := o.Raw(fmt.Sprintf("insert into mt_member_money_detail (uid,type,money,oid,`return`,addtime) "+
				"values ('%v','%v','%v','%v','%v','%v')", uid, 6, rprice, oid, 1, sword.Gettimes(""))).Exec(); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
				o.Rollback()
				return
			}

		case "2":
			if err := mobile.WxRefund(money_detail["id"].(string), rprice); err != nil {
				beego.Debug(err)
				// c.Data["json"] = 0
				// o.Rollback()
				// return
			}
		case "3":
			if err := mobile.AlipayRefund(money_detail["id"].(string), rprice); err != nil {
				beego.Debug(err)
				// c.Data["json"] = 0
				// o.Rollback()
				// return
			}
		}
	}
	c.Data["json"] = 1
	o.Commit()
	var r models.Mt_systems_record
	r.Tid, _ = strconv.Atoi(id)
	r.Way = 67
	r.Addtime = sword.Timeget()
	r.Table = 64
	r.Uid, _ = strconv.Atoi(c.Qid)
	if _, err := models.Orm().Insert(&r); err != nil {
		beego.Debug(err)
	}

}

type ActiveGbuyEnd struct {
	BaseController
}

func (c *ActiveGbuyEnd) Get() {
	if err := models.Exec(`update mt_active_gbuy set end=1 where id=` + c.GetString("id")); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
	var r models.Mt_systems_record
	r.Tid, _ = strconv.Atoi(c.GetString("id"))
	r.Way = 68
	r.Addtime = sword.Timeget()
	r.Table = 64
	r.Uid, _ = strconv.Atoi(c.Qid)
	if _, err := models.Orm().Insert(&r); err != nil {
		beego.Debug(err)
	}
	c.ServeJSON()
}

type ActiveGbuyPush struct {
	BaseController
}

func (c *ActiveGbuyPush) Get() {
	defer c.ServeJSON()
	vid := c.GetStrings("vid")
	id := c.GetString("id")
	content := c.GetString("content")
	vids := strings.Join(vid, `,`)
	product := models.Query(`select a.pid,b.title,a.price from mt_active_gbuy a left join mt_product b on a.pid=b.id where a.id=` + id)[0]
	data := map[string]map[string]interface{}{
		"first":    {"value": content, "color": "#1E90FF"},
		"keyword1": {"value": models.Systems()["name"], "color": "#333333"},
		"keyword2": {"value": product["title"], "color": "#333333"},
		"keyword3": {"value": product["price"], "color": "#333333"},
		"remark":   {"value": "团购活动正在火热进行中!", "color": "#DC143C"},
	}

	mem := models.Query(`select b.wx_openid_gzh from mt_member_vip_order a left join mt_member b on a.uid=b.id where a.vid in(` + vids + `)`)
	beego.Debug("mem", mem)
	for _, v := range mem {
		models.Push(fmt.Sprint(v["wx_openid_gzh"]), `JghVEqYW2gpPyGpdqEvhERS1AQUxTtsAwEQqjr8BOJI`, data, models.Urlc+"/mobile/column/product_content?id="+fmt.Sprint(product["pid"]), "")
	}
	c.Data["json"] = 1
}

type ActiveSales struct {
	BaseController
}

func (c *ActiveSales) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.gid=`+c.Gid)
	search := c.GetString("search")
	if search != "" {
		w = append(w, `(a.title like '%`+search+`%' or b.title like '%`+search+`%' or b.model like '%`+search+`%' or b.keywords like '%`+search+`%')`)
	}
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.sort desc,a.addtime desc`
	sql := `select a.*,b.title as pname,c.pathname from mt_active_sales a join mt_product b on a.pid=b.id left join mt_resources c 
	on b.img=c.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_active_sales a join mt_product b on a.pid=b.id where ` + ws
	info := models.Query(sql)
	for _, v := range info {
		if order := models.Query(`select count(a.id) as jnum,sum(b.num) as jgnum from mt_order a join mt_order_car b on a.carid=b.id 
			where a.type=2 and a.status>=2 and a.agid=` + v["id"].(string) + ` group by(a.id)`); order != nil {
			v["jnum"] = order[0]["jnum"]
			if order[0]["jgnum"] == nil {
				v["jgnum"] = "0"
			} else {
				v["jgnum"] = order[0]["jgnum"]
			}
		} else {
			v["jnum"] = "0"
			v["jgnum"] = "0"
		}
	}
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/active/sales?search=` + search + `&`
	c.TplName = "admin/active/sales.html"
}

type ActiveSalesAE struct {
	BaseController
}

func (c *ActiveSalesAE) Get() {
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.* from mt_active_sales a where a.id=` + id + ` and a.gid=` + c.Gid); info != nil {
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, "/admin/active/sales")
		}
	}
	c.TplName = "admin/active/sales_ae.html"
}
func (c *ActiveSalesAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	var old orm.Params
	var id = input.Get("id")
	input.Set("gid", c.Gid)
	if id == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	} else {
		old = models.Query(`select pid,price from mt_active_sales where id=?`, id)[0]
	}
	// var res int64
	if res, err := models.Save("mt_active_sales", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		if id != "" {
			if fmt.Sprint(old["price"]) != input.Get("price") {
				go FixPrice(fmt.Sprint(old["pid"]))
			}
		}
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 75
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type ActiveSalesEnd struct {
	BaseController
}

func (c *ActiveSalesEnd) Get() {
	if err := models.Exec(`update mt_active_sales set end=abs(end-1) where id=` + c.GetString("id")); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		go FixPrice(c.GetString("id"))
	}
	var r models.Mt_systems_record
	r.Tid, _ = strconv.Atoi(c.GetString("id"))
	r.Way = 68
	r.Addtime = sword.Timeget()
	r.Table = 75
	r.Uid, _ = strconv.Atoi(c.Qid)
	if _, err := models.Orm().Insert(&r); err != nil {
		beego.Debug(err)
	}
	c.ServeJSON()
}

func FixPrice(pid string) {
	product := models.Query(`
		select a.isvip,a.number,a.price,b.style,a.gid,a.bid 
		from mt_product a 
		left join mt_shop b on a.gid=b.id 
		where a.id=?`, pid)[0]
	var gid string
	price := fmt.Sprint(product["price"])
	isvip := fmt.Sprint(product["isvip"])
	style := fmt.Sprint(product["style"])
	number, _ := strconv.ParseFloat(fmt.Sprint(product["number"]), 64)
	nows := sword.Gettimes("")
	var tid = "0"
	if style == "0" || product["style"] == nil {
		gid = "0"
	} else {
		gid = fmt.Sprint(product["gid"])
	}
	if sales := models.Query(`
		select id,price 
		from mt_active_sales 
		where pid=? and status=1 and end=0 and starttime<? and endtime>?`, pid, nows, nows); sales != nil {
		price = fmt.Sprint(sales[0]["price"])
		tid = "2"
	}
	ordercar := models.Query(`select id,uid,num,price,spec,status from mt_order_car where pid=? and status<=2 `, pid)
	for _, v := range ordercar {
		uid := fmt.Sprint(v["uid"])
		//会员价
		var price2 = price
		var oldprice = fmt.Sprint(v["price"])
		var num = fmt.Sprint(v["num"])
		var spec = fmt.Sprint(v["spec"])
		if isvip == "1" && uid != "" {
			mem := models.Query(`
					select b.fold 
					from mt_member_vip_order a 
					join (select * from mt_member_vip where gid=? and status=1) b on a.vid=b.id 
					where a.uid=?`, gid, uid)
			if mem != nil {
				if fold := fmt.Sprint(mem[0]["fold"]); fold != "" && fold != "<nil>" {
					price2 = sword.Divi(sword.Mult(price2, fold), "100")
				}
			}
		}
		if v["status"] == "1" {
			if err := models.Exec(`update mt_order_car set price=?,type=? where id=?`, price2, tid, v["id"]); err != nil {
				beego.Debug(err)
			}
		} else {
			order := models.Query(`select id from mt_order where status=1 and concat(',',carid,',') like '%,` + fmt.Sprint(v["id"]) + `,%'`)
			if order != nil {
				if err := models.Exec(`update mt_order_car set price=?,type=? where id=?`, price2, tid, v["id"]); err != nil {
					beego.Debug(err)
				}
				brandFold := "100"
				brand := models.Query(`select fold from mt_brand_classify
					where find_in_set(?,uid) and find_in_set(?,bid) and status=1`, v["uid"], product["bid"])
				if brand != nil {
					if brand[0]["fold"] != nil {
						brandFold = brand[0]["fold"].(string)
					}
				}
				price2 = sword.Divi(sword.Mult(price2, brandFold), "100")
				oldprice = sword.Divi(sword.Mult(oldprice, brandFold), "100")
				oldprices := sword.Mult(num, oldprice)
				nowprices := sword.Mult(num, price2)
				oldpricei, _ := strconv.ParseFloat(oldprices, 64)
				nowpricei, _ := strconv.ParseFloat(nowprices, 64)
				cutprice := nowpricei - oldpricei
				if spec == "0" {
					cutprice *= number
				}
				if cutprice > 0 {
					if err := models.Exec(`update mt_order set money=money+? where id=?`, cutprice, order[0]["id"]); err != nil {
						beego.Debug(err)
					}
				} else {
					if err := models.Exec(`update mt_order set money=money-? where id=?`, math.Abs(cutprice), order[0]["id"]); err != nil {
						beego.Debug(err)
					}
				}
			}

		}

	}
}
